package com.car.web.controller;


import com.car.pojo.Role;
import com.car.pojo.SysUser;
import com.car.service.SysRoleMapperService;
import com.car.service.SysUserMapperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class RoleController {
    @Autowired
    private SysRoleMapperService sysRoleMapperService;
    @GetMapping(value = "/list_v2")
    public String list(Model model, Role role, @RequestParam(defaultValue = "1") Integer pageNo) {
        Integer pageSize =3;
        List<Role> list = sysRoleMapperService.list(role, pageSize, pageNo);
        model.addAttribute("list", list);
        Integer totalCount = sysRoleMapperService.selectSysUserCount(role);
        Integer totalPages = totalCount / pageSize;
        if (totalCount % pageSize != 0) {
            totalPages++;
        }
        model.addAttribute("list", list);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pageSize);
        return "index_v2";
    }

    @PostMapping("/add_v2")
    public String add(Role role) {
        int result = sysRoleMapperService.add(role);
        if (result > 0) {
            return "redirect:list_v2";
        }
        return "add_v2";
    }

    @GetMapping("/delete_v2")
    public String delete(@RequestParam Integer role_id) {
        int result = sysRoleMapperService.delete(role_id);
        if (result > 0) {
            return "redirect:list_v2";
        }
        return "delete_v2";
    }

    @PostMapping("/toEdit_v2")
    public String toEdit(Role role) {
        int result = sysRoleMapperService.update(role);
        if (result > 0) {
            return "redirect:list_v2";
        }
        return "index_v2";
    }

    @GetMapping("/edit_v2")
    public String edit(Model model, Integer role_id) {
        Role role = sysRoleMapperService.getByid(role_id);
        model.addAttribute("role", role);

        return "edit_v2";
    }
}
